#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

using std::cout;
using std::endl;

uint16_t client_port = 0;
std::string client_ip = "";
static void useage(const char *str)
{
    cout << "Useage:\n\t" << str << " ipaddr port\n"
         << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        useage(argv[0]);
        exit(-1);
    }
    // 创建套接字
    int client_socket = socket(AF_INET, SOCK_DGRAM, 0);
    if (client_socket < 0)
    {
        LogMessage(FATAL, "%d,%s", errno, strerror(errno));
        exit(-1);
    }
    // 获取ip和port
    client_port = atoi(argv[2]); // 转整形
    client_ip = argv[1];

    struct sockaddr_in dst_info;
    dst_info.sin_family = AF_INET;
    dst_info.sin_port = htons(client_port);
    dst_info.sin_addr.s_addr = inet_addr(client_ip.c_str());

    char read_buffer[1024];
    while (1)
    {
        std::string send_message;
        std::cout << "send message #:";
        std::getline(std::cin, send_message);

        if (send_message == "quit")
            break;
        
        // client向服务端发送数据时，OS会自动bind ip和端口
        sendto(client_socket, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&dst_info,sizeof(dst_info));

        //从服务端读回数据
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t read_size = recvfrom(client_socket,read_buffer,sizeof(read_buffer),0,(struct sockaddr *)&temp,&len);
        if(read_size > 0)
        {
            read_buffer[read_size] = 0;
            cout << "server echo #:" << read_buffer << endl;
        }
    }
    close(client_socket);
    return 0;
}